package com.yeskery.nut.script.function.common;

import com.yeskery.nut.script.function.BaseMultiParamFunction;

import java.util.logging.Logger;

/**
 * 字符串截取函数
 * @author sprout
 * 2022-05-17 14:33
 */
public class SubStringFunction extends BaseMultiParamFunction {

    private final static Logger logger = Logger.getLogger(SubStringFunction.class.getName());

    @Override
    public String getName() {
        return "subString";
    }

    @Override
    protected String doParams2(String[] params, String content) {
        String expression = params[0];
        int index = Integer.parseInt(params[1]);
        if (index < 0) {
            index = 0;
        } else if (index > expression.length()) {
            index = expression.length();
        }
        return expression.substring(index);
    }

    @Override
    protected String doParams3(String[] params, String content) {
        String expression = params[0];
        int startIndex = Integer.parseInt(params[1]);
        int endIndex = Integer.parseInt(params[2]);
        return getSubContent(expression, startIndex, endIndex);
    }

    @Override
    protected String doParams4(String[] params, String content) {
        String expression = params[0];
        String symbol = params[1];
        int index = expression.indexOf(symbol);
        if (index == -1 || index >= expression.length() - 1) {
            return expression;
        }
        String extendExpression = expression.substring(index + 1);
        int startIndex = Integer.parseInt(params[2]);
        int endIndex = Integer.parseInt(params[3]);
        return expression.substring(0, index + 1) + getSubContent(extendExpression, startIndex, endIndex);
    }

    /**
     * 获取截取字符串
     * @param content 字符串内容
     * @param startIndex 开始索引
     * @param endIndex 结束索引
     * @return 截取后的字符串
     */
    private String getSubContent(String content, int startIndex, int endIndex) {
        if (startIndex < 0) {
            startIndex = 0;
        }
        if (endIndex > content.length()) {
            endIndex = content.length();
        }
        if (startIndex >= endIndex) {
            logger.info("Function [" + getName() + "] Format Wrong Start Index Or End Index. At Expression: [" + content + "]");
            return content;
        }
        return content.substring(startIndex, endIndex);
    }
}
